package com.s1nx.back.service.impl;

import com.s1nx.back.dao.BookDao;
import com.s1nx.back.entity.Book;
import com.s1nx.back.exception.ServiceException;
import com.s1nx.back.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    @Override
    public List<Book> getAllBooks() {
        return bookDao.getAllBooks();
    }

    @Override
    public int deleteBook(int id) {
        Book book = bookDao.getBookById(id);
        if (book != null) {
            bookDao.deleteBookById(id);
            return 1;
        } else {
            throw new ServiceException("数据库无此书籍记录");
        }
    }

    @Override
    public int updateBook(Book book) {
        Book bookInDb = bookDao.getBookById(book.getId());
        if (bookInDb != null) {
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
            book.setUpdateTime(format);
            int id = bookDao.updateBookById(book);
            if (id > 0) {
                return 1;
            }
            throw new ServiceException("书籍信息更新失败");
        } else {
            throw new ServiceException("数据库无此书籍记录");
        }
    }

    @Override
    public int addBook(Book book) {
        Book bookByTitle = bookDao.getBookByTitle(book.getTitle());
        if (bookByTitle != null) {
            throw new ServiceException("已有【"+book.getTitle()+"】书籍记录");
        } else {
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
            book.setCreateTime(format);
            book.setUpdateTime(format);
            int id = bookDao.addBook(book);
            if (id > 0) {
                return 1;
            }
            throw new ServiceException("书籍信息添加失败");
        }
    }

}
